package fwx.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import fwx.dao.UserDao;
import fwx.model.User;
import fwx.util.DataSouceUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    private QueryRunner queryRunner = new QueryRunner(DataSouceUtil.getDataSource());
    //判断是否存在用户
    @Override
    public boolean exist(User user) {
        String sql = "select * from user where name = ? and password= ?";
        User user1;
        try{
           user1  = (User)queryRunner.query(sql,new BeanHandler<>(User.class),user.getName(),user.getPassword());
        }catch (SQLException e) {
            throw new RuntimeException(e);
        }
        if(user1 != null) {
            return true;
        }
        return false;
    }


    //添加用户
    public int addUser(User user) {
        String sql = "insert into user(name,password,admin) values(?,?,?)";
        int ret;
        //默认为普通用户
        user.setAdmin(0);
        try {
         ret = queryRunner.update(sql,user.getName(),user.getPassword(),user.getAdmin());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return ret;
    }

    @Override
    public int delete(int id) {
        String sql = "delete from user where id = ?";
        int i = 0;
        try {
            i = queryRunner.update(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return i;
    }
    //查询用户信息
    @Override
    public User findUser(User user) {
        String sql = "select * from user where name = ? and password= ?";
        User user1;
        try{
            user1  = (User)queryRunner.query(sql,new BeanHandler<>(User.class),user.getName(),user.getPassword());
        }catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return user1;
    }
    //查询用户信息
    @Override
    public User findUserByName(String userName) {
        String sql = "select * from user where name = ?";
        User user;
        try{
            user  = (User)queryRunner.query(sql,new BeanHandler<>(User.class),userName);
        }catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return user;
    }

    @Override
    public List<User> findUserAll() {
        String sql = "select * from user";
        List<User> list = new ArrayList<>();
        try {
            list = queryRunner.query(sql, new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

}
